import {
	defineStore
} from "pinia";
import { ref } from "vue"


type VoiceCallStore = {
	isCallIng ?: boolean;
	callList ?: any[];
	currentCall ?: any;
	// voiceCallAudioContext ?: any;
};
let voiceCallAudioContext : any = null;
const useVoiceCallStore = defineStore("voice-call-store", {
	persist: {
		// 仅在客户端使用
		paths: ['']
	},
	state: () : VoiceCallStore => ({
		isCallIng: false,
		callList: [],
		currentCall: null,
		// voiceCallAudioContext: null,
	}),

	getters: {
		currentCallRoomId: (state) => state.currentCall?.roomId || 0,
	},

	actions: {
		playVoiceCallAudio() {
			try {
				this.stopVoiceCallAudio();
				if (voiceCallAudioContext) {
					voiceCallAudioContext.play();
					console.log('播放', voiceCallAudioContext)
					this.$patch({
						isCallIng: true,
					});
				}
			} catch (e) {
				console.log(e)
				//TODO handle the exception
			}
		},
		stopVoiceCallAudio() {
			if (voiceCallAudioContext) {
				voiceCallAudioContext.startTime = 0;
				voiceCallAudioContext.stop();
			}
		},
		initVoiceCallAudioContext() {
			console.log('initAudioContext', this.isCallIng)
			try {
				if (!this.isCallIng) {
					console.log('开始初始化',)
					if (voiceCallAudioContext) {
						voiceCallAudioContext.pause();
						voiceCallAudioContext.destroy()
						voiceCallAudioContext = null
					}
					voiceCallAudioContext = uni.createInnerAudioContext();
					// innerAudioContext.src = wechatCallMp3;
					voiceCallAudioContext.src = 'https://lvshi.haidanet.com/uni-static/we-chat-video-call.mp3';
					voiceCallAudioContext.loop = true;
					// voiceCallAudioContext.play();

					console.log('初始化完成', voiceCallAudioContext)

					voiceCallAudioContext.onPlay(() => {
						console.log('开始播放');
					});
					voiceCallAudioContext.onStop(() => {
						console.log('停止播放');
					});
					voiceCallAudioContext.onError((res) => {
						console.log(res.errMsg);
						console.log(res.errCode);
					});

				}

			} catch (e) {
				console.log(e)
				//TODO handle the exception
			}
		},


		editCallStoreData(data : Partial<VoiceCallStore>) {
			this.$patch({
				...this.$state,
				...data,
			});
		},
	},
})

export default useVoiceCallStore;